package utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

public class MyHeaderFooter extends PdfPageEventHelper {
    // 总页数
    PdfTemplate totalPage;
    Font font12=new Font();

    {
        try {
            font12 = new Font(BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 9, Font.NORMAL);
            //font12 = new Font();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 打开文档时，创建一个总页数的模版
    public void onOpenDocument(PdfWriter writer, Document document) {
        PdfContentByte cb =writer.getDirectContent();
        totalPage = cb.createTemplate(30, 16);
    }
    // 一页加载完成触发，写入页眉和页脚
    public void onEndPage(PdfWriter writer, Document document) {
        PdfPTable table = new PdfPTable(3);
        try {
            table.setTotalWidth(PageSize.A4.getWidth()-80 );
            table.setWidths(new int[] { 20, 20, 3});
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(-10);
            table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            table.addCell(new Paragraph(writer.getPageNumber()%2==0?"       " + writer.getPageNumber():"", font12));// 可以直接使用addCell(str)，不过不能指定字体，中文无法显示
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(new Paragraph(writer.getPageNumber()%2!=0?"  " + writer.getPageNumber() : "", font12));
            PdfContentByte cb =writer.getDirectContent();
            totalPage = cb.createTemplate(30, 16);
            // 总页数
            PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
           cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
             //将页眉写到document中，位置可以指定，指定到下面就是页脚
            table.writeSelectedRows(0, -1, 40, PageSize.A4.getHeight() - 24, writer.getDirectContent());
            //table.writeSelectedRows(0, -1, 40, 40, writer.getDirectContent());
        } catch (Exception de) {
            throw new ExceptionConverter(de);
        }
    }
    // 全部完成后，将总页数的pdf模版写到指定位置
    public void onCloseDocument(PdfWriter writer, Document document) {
        String text = "";
        //ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,font12), 2, 2, 0);
    }


}

